//
//  MeUserInfoController.m
//  EFHealth
//
//  Created by nf on 15/7/2.
//  Copyright (c) 2015年 ef. All rights reserved.
//、
#import "EFNavigationController.h"
#import "LoginViewController.h"
#import "UserInfoViewController.h"
#import "ModifyPasswordController.h"
#import "MeUserInfoCell.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import "UserInfoEditModel.h"
#import "QiniuModel.h"
#import "QiniuSDK.h"
#import "QNEtag.h"

typedef enum editType{
    type_header ,
    type_name
}InfoEditType;


@interface UserInfoViewController ()<UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UITableViewDelegate,UITableViewDataSource,UITextViewDelegate,BaseModelProtocol>

@property (nonatomic,strong) UIImage *headerImg ;
@property (nonatomic,strong) UITableView *tableView ;

@property (nonatomic,strong) UIView *footerView ;

@property (nonatomic,strong) UIButton *logOutBtn ;

@property (nonatomic,strong) NSArray *titleArray ;
@property (nonatomic,strong) NSArray *subTitleArray ;

@property (nonatomic,strong) UITextField *TextField;

@property (nonatomic,strong) UserInfoEditModel *editModel;

@property (nonatomic,strong) QiniuModel *qiniuModel;
@property (nonatomic,strong) QiniuData *qiniuData;
@property (nonatomic,assign) InfoEditType editType;
@property (nonatomic,strong) NSString *headerUrl;

@end

@implementation UserInfoViewController


- (void)loginNoti
{
    [self.navigationController popViewControllerAnimated:NO];
//    self.tabBarController.selectedIndex = 0;
}

- (void)initView
{
    [super initView];
    [self.navBarView addTitle:@"个人信息"] ;
    
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.logOutBtn];

    [self getUserInfo];
    [self.qiniuModel getQiniuData];
}

- (void)getUserInfo{
    EFAppContext *appc = [EFAppContext sharedContext];
    self.subTitleArray = @[appc.headUrl,appc.userName,appc.mobile,@""];
}

- (void)getDataFinish:(BaseModel *)baseModel netResponse:(BaseResponse *)response{
    [self hideHUD];
    if ([baseModel isKindOfClass:[UserInfoEditModel class]])
    {
        [EFShowView showSueecssText:@"修改成功"];
        EFAppContext *appc = [EFAppContext sharedContext];
        if(self.editType == type_name){
            self.subTitleArray = @[appc.headUrl,self.TextField.text,appc.mobile,@""];
        }else if(self.editType == type_header){
            self.subTitleArray = @[self.headerUrl,appc.userName,appc.mobile,@""];
        }
        [self.tableView reloadData];
    }else if ([baseModel isKindOfClass:[QiniuModel class]])
    {
        QiniuResponse *resp = (QiniuResponse *)response;
        self.qiniuData = resp.resObject;
    }
}

- (void)logOutBtnClick{

    //清除用户信息
    [[EFAppContext sharedContext] clear];
    
    LoginViewController *login = [[LoginViewController alloc]init];
//    EFNavigationController *nav = [[EFNavigationController alloc]initWithRootViewController:login];
//    [self.navigationController presentViewController:nav animated:YES completion:nil];
    [self.navigationController pushViewController:login animated:YES];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.titleArray.count ;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10 ;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 1.0f ;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
   
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    view.backgroundColor = kColorDefultBg ;
    return view ;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50.0f ;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        NSString *cellIndentifier = [NSString stringWithFormat:@"MeUserInfoCell%zd%zd",indexPath.section,indexPath.row];//这里的cellID就是cell的xib对应的名称
        MeUserInfoCell *cell = (MeUserInfoCell *)[tableView dequeueReusableCellWithIdentifier:cellIndentifier];
        if(nil == cell) {
           cell = [[[NSBundle mainBundle] loadNibNamed:@"MeUserInfoCell" owner:nil options:nil] firstObject];
        }
    
        UIView *view_bg = [[UIView alloc]initWithFrame:cell.frame];
        view_bg.backgroundColor = [UIColor whiteColor];
        cell.selectedBackgroundView = view_bg;
        
        cell.title = self.titleArray[indexPath.section];
        cell.subTitle = self.subTitleArray[indexPath.section];
        cell.userIcon = indexPath.section==0 ;
        return cell ;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *tilte = self.titleArray[indexPath.section] ;

    if (ISEqual(tilte, @"头像")) {
        self.editType = type_header;
        UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"选择照片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相机",@"相册", nil];
        [actionSheet showInView:self.view];
    }else if (ISEqual(tilte, @"修改密码")) {
        ModifyPasswordController *pwdVC = [[ModifyPasswordController alloc]init];
        [self.navigationController pushViewController:pwdVC animated:YES];
    }else if (ISEqual(tilte, @"姓名")) {
        self.editType = type_name;
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"修改姓名" message:@"" preferredStyle:UIAlertControllerStyleAlert];
            //增加取消按钮
            UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
            //增加确定按钮
            UIAlertAction *alertB = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //获取第1个输入框；
                self.TextField = alertController.textFields.firstObject;
                //限制输入框字数
                [self.TextField addTarget:self action:@selector(alertTextAction:) forControlEvents:UIControlEventEditingChanged];
//                NSString *moneyStr = [NSString stringWithFormat:@"%@",self.TextField.text];
                NSLog(@"点击确定。。。。。。。。");
                EFAppContext *appContext = [EFAppContext sharedContext];
                [self.editModel changeWith:@"" name:self.TextField.text userId:appContext.authorization];
                
            }];
         
            //定义第一个输入框；
            [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
                textField.placeholder = @"请输入选项内容";
                textField.keyboardType = UIKeyboardTypeDefault;
            }];
         
            // 修改字体的颜色
            [alertA setValue:[UIColor colorWithRed:153/255.0f green:153/255.0f blue:153/255.0f alpha:1] forKey:@"_titleTextColor"];
            [alertB setValue:[UIColor blackColor] forKey:@"_titleTextColor"];
            [alertController addAction:alertA];
            [alertController addAction:alertB];
            
            [self presentViewController:alertController animated:true completion:nil];

    }
}


- (void)alertTextAction:(UITextField *)textField{
    if (textField == self.TextField) {
        if (textField.text.length > 15) {
            textField.text = [textField.text substringToIndex:15];
        }
    }
}

#pragma mark - 头像更改
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 0){
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            UIImagePickerController *c = [[UIImagePickerController alloc]init];
            c.sourceType = UIImagePickerControllerSourceTypeCamera;
            NSString *require = (__bridge NSString *)kUTTypeImage;
            c.mediaTypes = [[NSArray alloc]initWithObjects:require, nil];
            c.allowsEditing = YES ;
            c.delegate = self ;
            [self.navigationController presentViewController:c animated:YES completion:nil];
        }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"该设备不支持照相功能" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        }
        
    }
    if (buttonIndex == 1) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
            [imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            [imagePicker setAllowsEditing:YES];
            [imagePicker setDelegate:self];
            [self presentViewController:imagePicker animated:YES completion:nil];
        }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"该设备不支持调取图片库" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        }
    }
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    CGSize imagesize = image.size;
    if (imagesize.height>1000) {
        imagesize.height =imagesize.height/5;
        imagesize.width =imagesize.width/5;
        image = [self imageWithImage:image scaledToSize:imagesize];
    }
    
    //上传到服务器
//    [self showHUDWithLabel:@"头像修改中..."];
//    NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithCapacity:2];
//    EFAppContext *appc = [EFAppContext sharedContext];
//    //titleImg：视频封面图  save_path（上传路径）： ACTU 活动图片    ACVDO 活动视频    COTU 圈子图片   COVDO 圈子视频  AVATOR 头像
//    [parameters setValue:@"AVATOR" forKey:@"save_path"];
//    [parameters setValue:appc.ACCESS_TOKEN forKey:@"token"];
//    [parameters setValue:[PublicUtils md5Digest:appc.ACCESS_TOKEN] forKey:@"sign"];
//
//    NSString *url = [NSString stringWithFormat:@"%@rest/uploads/uploadfileIOS.html?token=%@&sign=%@",EFBaseURL,appc.ACCESS_TOKEN,[PublicUtils md5Digest:appc.ACCESS_TOKEN]];
//
//    [self uploadImage:url parameters:parameters image:image imageName:@"file_upload"];
//    [self dismissViewControllerAnimated:YES completion:NULL];
    
//    NSString *token = @"dWzkulw7ktQ5hAplkdbZ0W4rHDx3qeeCWcBAQWJ0:B_T9d2RJGO08AyV1jbHQn-wgxR8=:eyJzY29wZSI6Im15ZXRjIiwiZGVhZGxpbmUiOjE0NDIyMjg1NjZ9";
    
    NSString *token = self.qiniuData.token;
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    
    NSData *data = UIImagePNGRepresentation(image);
    
    //给图片设置上传时的唯一标示,也就是key，图片的名字.
    NSString *Qntag = [QNEtag data:data];
    NSLog(@"Qntag===%@", Qntag);
    
    //[@"Hello, World!" dataUsingEncoding : NSUTF8StringEncoding];
    
    [upManager putData:data key:[NSString stringWithFormat:@"%@"@"%@",@"data/upload/community/atlas/",Qntag] token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        NSLog(@"info===%@", info);
        NSLog(@"resp===%@", resp);
        NSString *headerUrl = [NSString stringWithFormat:@"%@/%@",self.qiniuData.qiNiuYunUrl,resp[@"key"]];
        NSLog(@"headerUrl===%@", headerUrl);
        self.headerUrl = headerUrl;
        EFAppContext *appc = [EFAppContext sharedContext];
        [self showHUDWithLabel:@"头像修改中..."];
        [self.editModel changeWith:headerUrl name:@"" userId:appc.authorization];
    } option:nil];
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
//对图片尺寸进行压缩--
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (void)uploadImage:(NSString*)path parameters:(NSDictionary*)parameters image:(UIImage*)image imageName:(NSString*)imageName
{
//    AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
//    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    manager.responseSerializer= [AFHTTPResponseSerializer serializer];
//    NSMutableArray *imageArr = [NSMutableArray array];
//    [imageArr addObject:image];
//    [manager POST:path parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//
//        int i = 0;
//        //根据当前系统时间生成图片名称
//        NSDate *date = [NSDate date];
//        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//        [formatter setDateFormat:@"yyyyMMddHHmmss"];
//        NSString *dateString = [formatter stringFromDate:date];
//
//        for (UIImage *imageTmp in imageArr) {
//            NSString *fileName = [NSString stringWithFormat:@"%@_%d.png", dateString, i];
//            NSData * imageData = UIImageJPEGRepresentation(imageTmp, 0.5);
//            // 这个地方有个注意点, 就是那个@"%@[]", 这个[] 是必须的, 它告诉后台我传送的是多张图片
//            [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"%@[]", @"file_upload"] fileName:fileName mimeType:@"image/png"];
//            i++;
//        }
//
//    } progress:^(NSProgress * _Nonnull uploadProgress) {
//
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//
//        NSLog(@"response = %@",responseObject);
//        NSString* newStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
//        NSLog(@"POST请求:%@",newStr);
//        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
//        NSLog(@"dic  = %@",dic);
//
//        NSArray *dataArray = dic[@"data"];
//        if ([dataArray isKindOfClass:[NSArray class]] && (dataArray.count>0)) {
//
//            NSDictionary *dict = dataArray[0];
//            NSString *imagePath = dict[@"path"];
//            [self.editPhotoModel editPhotoWithImageUrl:imagePath];
//        }
//
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//
//    }];

}
//- (AFHTTPSessionManager *)getClient
//{
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
//    return manager;
//}

- (void)saveHimgData:(NSData *)d
{
    //读取保存在沙盒中的数据
    //    NSData *data1=[NSData dataWithContentsOfFile:pStr];
    //    NSArray *array=[NSKeyedUnarchiver unarchiveObjectWithData:data1];
    //    [string addObjectsFromArray:array];
    //    NSData *d =
}

#pragma mark - textView代理方法
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
//    if ([textView.text isEqualToString:placeHolder]){
//        textView.text = @"";
//        textView.textColor = kTitleColor_black;
//    }
    return YES;
}
-(void)textViewDidEndEditing:(UITextView *)textView
{
//    if (textView.text.length == 0) {
//        textView.text = placeHolder;
//        textView.textColor = [UIColor lightGrayColor];
//    }
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
        return NO;
    }
    return YES;
}
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

- (UITableView *)tableView
{
    if (nil == _tableView) {
        _tableView = [[UITableView alloc ]initWithFrame:CGRectMake(0, KNavFullHeight, SCREEN_WIDTH, SCREEN_HEIGHT_EXCEPTNAV-80) style:UITableViewStyleGrouped];
//        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([MeUserInfoCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([MeUserInfoCell class])];
//        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([MeUserSexCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([MeUserSexCell class])];
        _tableView.dataSource = self ;
        _tableView.delegate = self ;
        _tableView.backgroundColor = kColorDefultBg ;
        
//        _tableView.tableFooterView = self.footerView;
        _tableView.contentSize = CGSizeMake(0, SCREEN_HEIGHT);
    }
    return _tableView ;
}

- (UIButton *)logOutBtn{
    
    if (nil == _logOutBtn) {
        
        _logOutBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, SCREEN_HEIGHT-80, SCREEN_WIDTH-60, 44)];
        _logOutBtn.layer.cornerRadius = 5;
        _logOutBtn.backgroundColor = UIColorFromRGB1(0xE5B580);
        [_logOutBtn setTitle:@"退出登录" forState:UIControlStateNormal];
        [_logOutBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_logOutBtn addTarget:self action:@selector(logOutBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _logOutBtn;
}
//
//- (NSString *)logSet:(NSSet *)dic {
//    if (![dic count]) {
//        return nil;
//    }
//    NSString *tempStr1 =
//    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
//                                                 withString:@"\\U"];
//    NSString *tempStr2 =
//    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
//    NSString *tempStr3 =
//    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
//    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
//    NSString *str =
//    [NSPropertyListSerialization propertyListFromData:tempData
//                                     mutabilityOption:NSPropertyListImmutable
//                                               format:NULL
//                                     errorDescription:NULL];
//    return str;
//}

//- (NSArray *)titleArray
//{
//    if (nil == _titleArray) {
//        _titleArray = @[@[@"昵称",@"头像"],@[@"性别",@"生日"],@[@"IP标签设置"],@[@"修改密码"],@[@"只允许好友可见"],@[@"版本更新",@"法律条款",@"关于加斯加"]];
//    }
//    return _titleArray ;
//}

- (NSArray *)titleArray
{
    if (nil == _titleArray) {
        _titleArray = @[@"头像",@"姓名",@"手机号",@"修改密码"];
    }
    return _titleArray ;
}

- (UserInfoEditModel *)editModel{

    if (nil == _editModel) {
        _editModel = [[UserInfoEditModel alloc]initWithDelegate:self cache:NO];
    }
    return _editModel;
}

- (QiniuModel *)qiniuModel{

    if (nil == _qiniuModel) {
        _qiniuModel = [[QiniuModel alloc]initWithDelegate:self cache:NO];
    }
    return _qiniuModel;
}

@end



